﻿<%@ WebHandler Language="C#" Class="RbCompleteSetRateChartDashBoard" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;
using System.Net;

/*
 * Description: 热表厂齐套性检查趋势看板
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2024.10.16
 */

public class RbCompleteSetRateChartDashBoard : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                DataTable dtResult = new DataTable();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getDetail":
                        r = getDetail(jObject);
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    Result getData(JObject jObject)
    {
        string sql = @"
SELECT m.monthday,EXTRACT(DAY FROM m.monthday) day,n.*
FROM
(
  SELECT TRUNC(TO_DATE('{0}', 'yyyy-mm'), 'MONTH') + (ROWNUM - 1) monthday
  FROM dual
  CONNECT BY ROWNUM <= (LAST_DAY(TO_DATE('{0}', 'yyyy-mm')) - TRUNC(TO_DATE('{0}', 'yyyy-mm'), 'MONTH') + 1)
) m
LEFT JOIN 
(
     SELECT  trunc(d.startdate) starttime,EXTRACT(DAY FROM d.startdate) DAY,
             COUNT(1) total,
             SUM(DECODE(d.workflow,'是',1,0)) workflow,
             SUM(DECODE(d.material,'是',1,0)) material,
             SUM(DECODE(d.aps,'是',1,0)) aps,
             SUM(DECODE(d.resources,'是',1,0)) resources,
             SUM(DECODE(d.spotcheck,'是',1,0)) spotcheck,
             SUM(DECODE(d.tool,'是',1,0)) tool,
             ROUND(SUM(DECODE(d.workflow,'是',1,0)) / COUNT(1),4) * 100 workflowRate,
             ROUND(SUM(DECODE(d.material,'是',1,0)) / COUNT(1),4) * 100 materialRate,
             ROUND(SUM(DECODE(d.aps,'是',1,0)) / COUNT(1),4) * 100 apsRate,
             ROUND(SUM(DECODE(d.resources,'是',1,0)) / COUNT(1),4) * 100 resourcesRate,
             ROUND(SUM(DECODE(d.spotcheck,'是',1,0)) / COUNT(1),4) * 100 spotcheckRate,
             ROUND(SUM(DECODE(d.tool,'是',1,0)) / COUNT(1),4) * 100 toolRate,
             ROUND(SUM(DECODE(d.quality,'是',1,0)) / COUNT(1),4) * 100 qualityRate,
             ROUND(SUM(DECODE(d.ncprogram,'是',1,0)) / COUNT(1),4) * 100 ncProgramRate
    FROM ({1}) d
    GROUP BY d.startdate
) n ON n.starttime = m.monthday
ORDER BY m.monthday";
        sql = string.Format(sql, jObject["yearmonth"].ToString(), getSql(jObject));
        DataTable dtResult = dal.GetDataTable(sql);
        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(dtResult.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    // 查询未齐套明细
    Result getDetail(JObject jObject)
    {
        string sql = getSql(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    string getSql(JObject obj)
    {
        string factoryid = "", workcenterid = "", teamid = "";
        JArray selectOrg = JArray.Parse(obj["selectOrg"].ToString());
        if (selectOrg.Count == 3)
        {
            factoryid = selectOrg[0].ToString();
            workcenterid = selectOrg[1].ToString();
            teamid = selectOrg[2].ToString();
        }
        else if (selectOrg.Count == 2)
        {
            factoryid = selectOrg[0].ToString();
            workcenterid = selectOrg[1].ToString();
        }
        else
        {
            factoryid = selectOrg[0].ToString();
        }
        string sql = @"
SELECT t.containerid,cci.containername,ws.workflowstepname,f2.factoryname fromfactoryname,TRUNC(aps.starttime) startdate,aps.starttime,aps.endtime,f.factoryname,w.workcentername,te.teamname,
       st.spectypename,t.iscompaps,t.iscompmaterial,t.iscompresource,t.iscompspotcheck,t.iscomptool,t.iscompworkflow,--t.iscompquality,
       DECODE(t.iscompaps,1,'是','否') aps,
       DECODE(t.iscompmaterial,1,'是','否') material,
       DECODE(t.iscompresource,1,'是','否') resources,
       DECODE(t.iscompspotcheck,1,'是','否') spotcheck,
       DECODE(t.iscomptool,1,'是','否') tool,
       DECODE(t.iscompworkflow,1,'是','否') workflow,
       --DECODE(t.iscompquality,1,'是','否') quality,
       --CASE WHEN EXISTS (
       --  SELECT 1 
       --  FROM containersubcontainer csc
       --  LEFT JOIN containercurrentinfo subc ON subc.containerid = csc.containerid
       --  WHERE csc.containerid = t.containerid AND csc.workflowstepname = ws.workflowstepname AND subc.containerstatus = 1
       --        AND EXISTS (SELECT 1 
       --                    FROM containercheckinfo2 cci 
       --                    WHERE cci.containerid = subc.containerid AND cci.isuse = 0 AND cci.rectifymeasures != '100%')
       --) THEN '否' ELSE '是' END quality,
       CASE WHEN csc.qualityRate<>'100' THEN '否' ELSE '是' END quality,
       '是' ncprogram,
       SUM(NVL(csd.lossqty,0)) lossqty,
       SUM(NVL(csd.reworkqty,0)) reworkqty
FROM shipconcompletesetsnapshot t
INNER JOIN apsplandetail aps ON t.containerid = aps.containerid AND aps.workflowstepid = t.workflowstepid AND aps.isuse = 0
LEFT JOIN factory f ON f.factoryid = aps.specfactoryid
LEFT JOIN containercurrentinfo cci ON cci.containerid = t.containerid
LEFT JOIN workflowstep ws ON ws.workflowstepid = t.workflowstepid
LEFT JOIN workcenter w ON w.workcenterid = aps.workcenterid
LEFT JOIN team te ON te.teamid = aps.teamid
LEFT JOIN factory f2 ON f2.factoryid = cci.originalfactoryid
LEFT JOIN spec s ON s.specid = aps.specid
LEFT JOIN spectype st ON st.spectypeid = s.spectypeid
LEFT JOIN containersteprecord csd ON csd.containerid = t.containerid AND t.workflowstepid = csd.workflowstepid
LEFT JOIN (
     SELECT fcci.productname,csc.workflowstepname,ROUND(SUM(decode(subcc.rectifymeasures,'100%',1,0))/COUNT(1),4)*100 qualityRate 
     FROM containercheckinfo2 subcc 
     LEFT JOIN containercurrentinfo subcci ON subcci.containerid =subcc.containerid
     LEFT JOIN containersubcontainer csc ON csc.subcontainerid =subcci.containerid
     LEFT JOIN containercurrentinfo fcci ON fcci.containerid =csc.containerid 
     WHERE ((subcc.lossreason='责任报废' AND NVL(subcc.lossqty,0)!=0) OR NVL(subcc.reworkqty,0)!=0)
     AND subcci.containerstatus =1 AND subcci.originalfactoryid ='0004e2800000281c' AND subcc.isuse =0
     GROUP BY fcci.productname ,csc.workflowstepname   
) csc ON csc.productname=cci.productname AND csc.workflowstepname=ws.workflowstepname
WHERE TRUNC(aps.starttime) <= TRUNC(SYSDATE)";
        if (factoryid != "")
        {
            sql += string.Format(" AND aps.specfactoryid = '{0}'", factoryid);
        }

        if (workcenterid != "")
        {
            sql += string.Format(" AND w.workcenterid = '{0}'", workcenterid);
        }

        if (teamid != "")
        {
            sql += string.Format(" AND te.teamid = '{0}'", teamid);
        }

        if (obj["startOfSelectMonth"] != null && obj["startOfSelectMonth"].ToString() != "")
        {
            sql += string.Format(" AND aps.starttime >= TO_DATE('{0} 00:00:00','yyyy-mm-dd hh24:mi:ss') ", obj["startOfSelectMonth"].ToString());
        }

        if (obj["endOfSelectMonth"] != null && obj["endOfSelectMonth"].ToString() != "")
        {
            sql += string.Format(" AND aps.starttime <= TO_DATE('{0} 23:59:59','yyyy-mm-dd hh24:mi:ss') ", obj["endOfSelectMonth"].ToString());
        }

        if (obj["date"] != null && obj["date"].ToString() != "")
        {
            sql += string.Format(" AND TRUNC(aps.starttime) <= TO_DATE('{0}','yyyy-mm-dd') ", obj["date"].ToString());
        }

        if (obj["seriesName"] != null)
        {
            string seriesName = obj["seriesName"].ToString();
            if (seriesName == "workflowrate")
            {
                sql += " AND t.iscompworkflow = 0";
            }
            if (seriesName == "apsrate")
            {
                sql += " AND t.iscompaps = 0";
            }
            if (seriesName == "toolrate")
            {
                sql += " AND t.iscomptool = 0";
            }
            if (seriesName == "materialrate")
            {
                sql += " AND t.iscompmaterial = 0";
            }
            if (seriesName == "resourcesrate")
            {
                sql += " AND t.iscompresource = 0";
            }
            if (seriesName == "spotcheckrate")
            {
                sql += " AND t.iscompspotcheck = 0";
            }
            if (seriesName == "qualityrate")
            {
                //sql += " AND NVL(t.iscompquality,0) = 0";
            }
        }
        sql += @"
GROUP BY t.containerid,cci.containername,ws.workflowstepname,f2.factoryname,aps.starttime,aps.starttime,
         aps.endtime,f.factoryname,w.workcentername,te.teamname,st.spectypename,--t.iscompquality,
         t.iscompaps,t.iscompmaterial,t.iscompresource,t.iscompspotcheck,t.iscomptool,t.iscompworkflow,csc.qualityRate
";
        if (obj["seriesName"] != null)
        {
            if (obj["seriesName"].ToString() == "qualityrate")
            {
                sql = string.Format("select w.* from ({0}) w WHERE w.quality = '否'", sql);
            }
        }
        return sql;
    }

    //导出
    void exportExcel(JObject jObject)
    {
        string sql = getSql(jObject);
        DataTable dt = dal.GetDataTable(sql);
        dt.Columns.Remove("factoryname");
        dt.Columns.Remove("workcentername");
        dt.Columns.Remove("teamname");
        dt.Columns.Remove("iscompaps");
        dt.Columns.Remove("iscompmaterial");
        dt.Columns.Remove("iscompresource");
        dt.Columns.Remove("iscompspotcheck");
        dt.Columns.Remove("iscomptool");
        dt.Columns.Remove("iscompworkflow");
        dt.Columns.Remove("startdate");
        dt.Columns.Remove("iscompquality");
        dt.Columns.Remove("ncprogram");

        dt.Columns["containername"].Caption = "批次号";
        dt.Columns["workflowstepname"].Caption = "工序";
        dt.Columns["fromfactoryname"].Caption = "主制分厂";
        dt.Columns["starttime"].Caption = "转工计划开始时间";
        dt.Columns["endtime"].Caption = "转工计划完成时间";
        dt.Columns["spectypename"].Caption = "工艺类型";
        dt.Columns["aps"].Caption = "排产数据齐套";
        dt.Columns["material"].Caption = "生产物资齐套";
        dt.Columns["resources"].Caption = "设备状态齐套";
        dt.Columns["spotcheck"].Caption = "特殊过程齐套";
        dt.Columns["tool"].Caption = "工装工具齐套";
        dt.Columns["workflow"].Caption = "工艺路线齐套";
        dt.Columns["workflow"].Caption = "工艺路线齐套";
        dt.Columns["quality"].Caption = "质量预警";
        dt.Columns["lossqty"].Caption = "报废数";
        dt.Columns["reworkqty"].Caption = "返修数";
        ExportHelper.ExportExcel(dt, jObject["title"].ToString() + "导出");
    }
}